package com.jus.player.activity;

import static com.jus.player.api.OkHttpHelper._DATA;
import static com.jus.player.api.OkHttpHelper._TOKEN;
import static com.jus.player.util.CommonUtils.checkFacebookAvailable;
import static com.jus.player.util.CommonUtils.hideLoading;
import static com.jus.player.util.CommonUtils.isGoogleServicesAvailable;
import static com.jus.player.util.CommonUtils.isNetworkConnected;
import static com.jus.player.util.CommonUtils.showLoading;
import static com.jus.player.util.CommonUtils.showToast;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.alibaba.fastjson2.JSONObject;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.Task;
import com.jus.player.R;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.config.AppConfig;
import com.jus.player.util.CommonUtils;
import com.jus.player.util.StringUtils;
import com.jus.player.util.Utils;
import com.jus.player.util.view.HookCheckBox;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

public class LoginActivity extends BaseActivity {

    // UI组件
    private Button btnLogin;
    private Button googleLogin;
    private Button facebookLogin;
    private LoginButton loginButton;
    private HookCheckBox vHookCheckBox;

    // 状态控制
    private final AtomicBoolean isLoginInProgress = new AtomicBoolean(false);
    private final AtomicBoolean selectedBox = new AtomicBoolean(false);

    // 请求码
    private static final int RC_SIGN_IN_CODE = 9090;
    private static final int REQUEST_USER_AGREEMENT = 1;
    private static final int REQUEST_PRIVACY_POLICY = 2;

    // 登录类型
    private String loginType;

    // 第三方登录相关
    private CallbackManager callbackManager;
    private GoogleSignInClient mGoogleSignInClient;
    private final List<String> permissions = Arrays.asList("public_profile", "email");

    // 超时处理
    private Handler handler;
    private Runnable timeoutRunnable;
    private static final long LOGIN_TIMEOUT_MS = 15000; // 10秒超时

    private boolean isUserAgreementAgreed = false;
    private boolean isPrivacyPolicyAgreed = false;

    @Override
    protected int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        btnLogin = findViewById(R.id.btn_ones_login);
        googleLogin = findViewById(R.id.btn_google_login);
        facebookLogin = findViewById(R.id.btn_facebook_login);
        loginButton = findViewById(R.id.login_button);
        vHookCheckBox = findViewById(R.id.hook_checkbox);

        // 初始化第三方登录
        initThirdPartyLogin();
    }

    @Override
    protected void initData() {
        // 检查是否已登录
        if (!StringUtils.isEmpty(CommonUtils.findFromSp(this, _TOKEN))) {
            navigateToMainActivity();
            return;
        }
        setupClickListeners();
    }

    /**
     * faceBook登陆初始化方法
     */
    private void initThirdPartyLogin() {
        // 初始化Google登录客户端
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.web_oauth_client_id))
                .requestEmail()
                .build();
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        //初始化facebook
        callbackManager = CallbackManager.Factory.create();
        loginButton.setPermissions(permissions);
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                handleFacebookLoginSuccess(loginResult.getAccessToken());
            }

            @Override
            public void onCancel() {
                handleLoginCancel();
                //---
                // 用户取消登录
                Log.e("FACE_BOOK登陆", "登陆取消");
                showToast(LoginActivity.this, getString(R.string.hint_login_cancel));
            }

            @Override
            public void onError(@NonNull FacebookException e) {
                handleFacebookLoginError(e);
                //---
                // 登录出错
                Log.d("FACE_BOOK登陆", "registerCallback.onError" + e.getMessage());
                if (e instanceof FacebookAuthorizationException) {
                    if (AccessToken.getCurrentAccessToken() != null) {
                        // 如果当前用户已登录，且fb登陆验证异常，则调fb的登出
                        LoginManager.getInstance().logOut();
                    }
                }
                showToast(LoginActivity.this, "登陆异常:" + e.getMessage());
            }
        });
    }

    /**
     * 登陆页面点击事件监听
     */
    private void setupClickListeners() {

        // 一键登录
        btnLogin.setOnClickListener(v -> {
            if (checkLoginPreconditions()) return;
            performDeviceLogin();
        });

        // Google登录
        googleLogin.setOnClickListener(v -> {
            if (checkLoginPreconditions()) return;
            startGoogleLogin();
        });

        // Facebook登录
        facebookLogin.setOnClickListener(v -> {
            if (checkLoginPreconditions()) return;
            startFacebookLogin();
        });

        // 协议勾选框
        vHookCheckBox.setOnCheckChangeListener(isCheck -> selectedBox.set(isCheck));

        // 用户协议和隐私政策
        TextView userAgreement = findViewById(R.id.userAgreement);
        TextView privacyPolicy = findViewById(R.id.privacyPolicy);

        userAgreement.setOnClickListener(v -> openAgreement(REQUEST_USER_AGREEMENT));
        privacyPolicy.setOnClickListener(v -> openAgreement(REQUEST_PRIVACY_POLICY));
    }

    //检查登陆前提条件
    private boolean checkLoginPreconditions() {
        if (!selectedBox.get()) {
            showToast(this, getString(R.string.hint_login_select));
            return true;
        }
        if (isLoginInProgress.get()) {
            showToast(this, getString(R.string.login_in_progress));
            return true;
        }
        if (!isNetworkConnected(this)) {
            showNetworkError();
            return true;
        }
        return false;
    }

    //执行设备登陆
    private void performDeviceLogin() {
        loginType = "设备登陆";
        @SuppressLint("HardwareIds")
        String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        Log.d("LoginActivity", "Device login with ID: " + androidId);
        deviceLogin(androidId);
    }

    /**
     * google登陆方法
     */
    private void startGoogleLogin() {
        isLoginInProgress.set(true);
        showLoading(this);

        //检测google 服务不可用
        isGoogleServicesAvailable(this, isAvailable -> {
            hideLoading(LoginActivity.this);
            if (!isAvailable) {
                isLoginInProgress.set(false);
                showGoogleServicesError();
                return;
            }
            loginType = AppConfig.GOOGLE_LOGIN;
            startGoogleSignInWithTimeout();
        });
    }

    // Facebook登陆
    private void startFacebookLogin() {
        isLoginInProgress.set(true);
        showLoading(this);

        checkFacebookAvailable(this, isAvailable -> {
            hideLoading(LoginActivity.this);
            if (!isAvailable) {
                isLoginInProgress.set(false);
                showGoogleServicesError();
                return;
            }

            loginType = AppConfig.FACE_BOOK_LOGIN;
            loginButton.performClick();
            LoginManager.getInstance().logInWithReadPermissions(this, permissions);
        });
    }

    // Google登陆超时
    private void startGoogleSignInWithTimeout() {
        showLoading(this);
        handler = new Handler(Looper.getMainLooper());
        timeoutRunnable = () -> {
            if (!isFinishing()) {
                hideLoading(LoginActivity.this);
                showTimeoutError();
                isLoginInProgress.set(false);
            }
        };
        handler.postDelayed(timeoutRunnable, LOGIN_TIMEOUT_MS);
        startActivityForResult(mGoogleSignInClient.getSignInIntent(), RC_SIGN_IN_CODE);
    }

    // Face登陆成功后获取用户信息
    private void handleFacebookLoginSuccess(AccessToken accessToken) {
        GraphRequest request = GraphRequest.newMeRequest(accessToken, (object, response) -> {
            try {
                String name = object.getString("name");
                String email = object.getString("email");
                String id = object.getString("id");
                String profilePicUrl = "https://graph.facebook.com/" + id + "/picture?type=large";

                registerThirdPartyUser(name, email, profilePicUrl, accessToken.getToken());
            } catch (Exception e) {
                handleLoginError("获取用户信息异常：" + e.getMessage());
            }
        });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email");
        request.setParameters(parameters);
        request.executeAsync();
    }

    private void handleFacebookLoginError(FacebookException e) {
        Log.e("FacebookLogin", "Error: " + e.getMessage());
        if (e instanceof FacebookAuthorizationException && AccessToken.getCurrentAccessToken() != null) {
            LoginManager.getInstance().logOut();
        }
        handleLoginError("Facebook登录异常: " + e.getMessage());
    }

    private void handleLoginCancel() {
        Log.d("LoginActivity", loginType + "登录取消");
        isLoginInProgress.set(false);
        showToast(this, getString(R.string.hint_login_cancel));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 处理超时
        if (handler != null) {
            handler.removeCallbacks(timeoutRunnable);
        }
        // Facebook回调
        callbackManager.onActivityResult(requestCode, resultCode, data);

        // Google登录结果
        if (requestCode == RC_SIGN_IN_CODE) {
            handleGoogleSignInResult(GoogleSignIn.getSignedInAccountFromIntent(data));
        }
        // 协议同意结果
        if (resultCode == RESULT_OK && data != null) {
            handleAgreementResult(requestCode, data.getBooleanExtra("agreed", false));
        }
    }

    private void handleGoogleSignInResult(Task<GoogleSignInAccount> task) {
        try {
            GoogleSignInAccount account = task.getResult(ApiException.class);
            if (account != null) {
                Uri uri = account.getPhotoUrl();
                String url = uri != null ? uri.toString() : null;
                registerThirdPartyUser(
                        account.getDisplayName(),
                        account.getEmail(), url,
                        account.getIdToken()
                );
            } else {
                handleLoginError("Google账号信息为空");
            }
        } catch (ApiException e) {
            handleLoginError("Google登录失败: " + e.getMessage());
            Log.w("GoogleSignIn", "signInResult:failed code=" + e.getStatusCode());
        }
    }

    //
    private void openAgreement(int requestCode) {
        Class<?> targetClass = requestCode == REQUEST_USER_AGREEMENT ?
                UserAgreementActivity.class : PrivacyPolicyActivity.class;
        startActivityForResult(new Intent(this, targetClass), requestCode);
    }

    // 处理用户协议勾选结果
    private void handleAgreementResult(int requestCode, boolean agreed) {
        if (requestCode == REQUEST_USER_AGREEMENT) {
            isUserAgreementAgreed = agreed;
        } else if (requestCode == REQUEST_PRIVACY_POLICY) {
            isPrivacyPolicyAgreed = agreed;
        }
        autoCheckAgreementBox();
    }

    private void autoCheckAgreementBox() {
        if (isUserAgreementAgreed && isPrivacyPolicyAgreed) {
            runOnUiThread(() -> {
                vHookCheckBox.setCheck(true);
                vHookCheckBox.invalidate();// 强制刷新视图
                vHookCheckBox.requestLayout();// 请求重新布局
            });
        }
    }

    // 报错第三方登陆信息
    private void registerThirdPartyUser(String nickname, String email, String avatarUrl, String token) {
        Map<String, Object> params = new HashMap<>();
        params.put("nickname", nickname);
        params.put("email", email);
        params.put("token", token);
        params.put("signature", loginType);
        params.put("loginIp", Utils.getIPAddress(this));
        params.put("headThumbUrl", avatarUrl);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.put("loginTime", LocalDateTime.now());
        }
        performRegistration(ApiConfig.REGISTER, params);
    }

    // 设备登陆参数
    private void deviceLogin(String androidId) {
        Map<String, Object> params = new HashMap<>();
        params.put("signature", loginType);
        params.put("username", androidId);
        params.put("loginIp", Utils.getIPAddress(this));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.put("loginTime", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        }

        performRegistration(ApiConfig.REGISTER, params);
    }

    private void performRegistration(String endpoint, Map<String, Object> params) {
        showLoading(this);
        isLoginInProgress.set(true);

        OkHttpHelper.getInstance(this).postJsonAsync(endpoint, params, new OkHttpHelper.HttpCallback() {
            @Override
            public void onSuccess(String response) {
                CommonUtils.insertToSp(LoginActivity.this, loginType, String.valueOf(params.get("email")));
                handleRegistrationSuccess(response);
            }

            @Override
            public void onFailure(OkHttpHelper.HttpException e) {
                handleLoginError(e.getMessage());
            }
        });
    }

    // 登陆成功操作
    private void handleRegistrationSuccess(String response) {
        hideLoading(LoginActivity.this);
        isLoginInProgress.set(false);
        JSONObject resJo = JSONObject.parseObject(response);
        String token = resJo.getString(_DATA);
        if (token != null) {
            CommonUtils.insertToSp(LoginActivity.this, _TOKEN, token);
            navigateToMainActivity();
        } else {
            handleLoginError("登录错误: 令牌为空");
        }
    }

    private void handleLoginError(String message) {
        runOnUiThread(() -> {
            hideLoading(LoginActivity.this);
            isLoginInProgress.set(false);
            showToast(LoginActivity.this, message);
        });
    }

    // 导航到主页面
    private void navigateToMainActivity() {
        CommonUtils.navigateTo(this, MainActivity.class,
                Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        finish();
    }

    private void showNetworkError() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.network_error_title)
                .setMessage(R.string.network_error_message)
                .setPositiveButton(R.string.ok, null)
                .show();
    }

    private void showGoogleServicesError() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.network_error_title)
                .setMessage(R.string.network_error_message)
                .setPositiveButton(R.string.ok, null)
                .show();
    }

    private void showTimeoutError() {
        runOnUiThread(() -> new AlertDialog.Builder(this)
                .setTitle(R.string.timeout_title)
                .setMessage(R.string.timeout_message)
                .setPositiveButton(R.string.retry, (dialog, which) -> startGoogleSignInWithTimeout())
                .setNegativeButton(R.string.cancel, null)
                .show());
    }

    @Override
    protected void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }

}